/*
  Example usage:

    <div class="Form">
        <div class="FormItem" data-label="First name">
            <input>
        </div>
        <div class="FormItem" data-label="Last name">
            <input>
        </div>
    </div>
*/
$(function() {

    var $formList = $(".Form");

    for(x=0; x<$formList.length; x++) {

        $form = $($formList[x]);

        var spacer = createSpacer($form);

        addSpaceToChildren($form, spacer);

        setFormLabelWidths($form);
    }

    function createSpacer($form) {

        var gap = $form.attr("data-gap");

        if(!gap) {
            gap = "5px";
        }

        var spacer = "<div style='height: " + gap + "'></div>";

        return spacer;
    }

    function addSpaceToChildren($form, spacer) {

        var $children = $form.children();
        $form.empty();

        if($children.length > 0) {
            $form.append($children[0]);
        }

        if($children.length > 1) {
            for(y=1; y<$children.length; y++) {
                var child = $children[y];
                $form.append(spacer);
                $form.append(child);
            }
        }
    }

    function setFormLabelWidths($form) {

        var labelWidth = $form.attr("data-labelWidth");

        if(!labelWidth) {
            labelWidth = "200px";
        }

        var $formItemList = $(".FormItem", $form);

        for(x=0; x<$formItemList.length; x++) {

            var $formItem = $($formItemList[x]);

            var label = $formItem.attr("data-label");

            $formItem.prepend("<div style='display: inline-block; width: " + labelWidth + "'>" + label + "</div> ");
        }
    }
});
